<?php
namespace app\repair\model;
use app\common\model\Common;
use think\Db;
use think\Exception;
class RepairGoods extends Common
{
	protected $table = 'mps_repair_goods';
	protected $append = ['category_name','cate_name','old_num'];
	
	/**
	 * 维修配件 排序统计列表
	 * @param  array 	$goodsWhere 	配件查询条件
	 * @param  array 	$orderWhere 	维修单查询条件
	 * @param  string 	$order_name  	统计条件
	 * @param  intger 	$page 			当前页数
	 * @param  intger 	$row  			每页条数
	 */
	public function partsList($goodsWhere, $orderWhere,$order_name, $page, $row)
	{
		switch($order_name){
			case 'order_num': return $this->orderNumSort($goodsWhere, $orderWhere,$page, $row);break;
			default: return [];break;
		}
	}
	/**
	 * 维修配件 数排序列表 总数
	 * @param  array 	$goodsWhere 	配件查询条件
	 * @param  string 	$order_name  	统计条件
	 */
	public function partsCount($goodsWhere, $order_name)
	{
		switch($order_name){
			case 'order_num': return $this->orderNumCount($goodsWhere);break;
			default: return 0;break;
		}
	}

	/**
	 * 维修配件
	 * 订单数排序 总数
	 * @param  [type] $goodsWhere [description]
	 * @return [type]        [description]
	 */
	private function orderNumCount($goodsWhere)
	{
		return Db::name('goods')
		->alias('g')
		->where('g.category_id',config('parameter.repair_cat_id'))
		->where('g.is_show',0)
		->where($goodsWhere)
		->count();
	}
	/**
	 * 维修配件
	 * 订单数排序列表
	 * @param  array $goodsWhere 配件查询条件
	 * @param  array $orderWhere 维修单查询条件
	 * @param  intger $page 当前页数
	 * @param  intger $row  每页条数
	 */
	private function orderNumSort($goodsWhere, $orderWhere,$page, $row)
	{
		$repairGoods = $this->getFinishGoods($orderWhere);
		return Db::name('goods')
		->alias('g')
		->join('mps_stock s','g.goods_id = s.goods_id','LEFT')
		->join($repairGoods,'g.goods_id = srg.goods_id','LEFT')
		->field('s.buying_price,g.goods_name,g.brand_name,g.marker,g.colour_name,g.selling_price,g.trade_price,ifnull(srg.num,0) as num,"维修配件" as cate_name')
		->where('g.category_id',config('parameter.repair_cat_id'))
		->where('g.is_show',0)
		->where($goodsWhere)
		->order('srg.num desc,g.goods_id desc')
		->group('g.goods_id')
		->page($page, $row)
		->select();
	}
	/**
	 * 获取完成维修单的维修配件
	 */
	private function getFinishGoods($orderWhere)
	{
		$sql = Db::name('repair')
		->alias('r')
		->join('mps_repair_goods rg','rg.repair_id = r.repair_id','LEFT')
		->field('count(rg.repair_id) as num,rg.goods_id')
		->where('r.state',8)
		->where($orderWhere)
		->group('rg.goods_id')
		->select(false);
		return "($sql) as srg";
	}
	/**
	 * 未扣库存时
	 * 添加维修配件
	 * @param array $goods     商品信息
	 * @param intger $repair_id 维修单id
	 * @param string $repair_id 维修单id
	 */
	public function addRepairGoods($goods, $repair_id, $repair_sn)
	{
		$data = [];
		foreach($goods as $k => $v){
			$data[] = [
				'repair_id'		=> $repair_id,
				'goods_id'		=> $v['goods_id'],
				'goods_sn'		=> $v['goods_sn'],
				'goods_name'	=> $v['goods_name'],
				'number'		=> $v['num'],
				'unit'			=> $v['unit'],
				'selling_price'	=> $v['selling_price'],
				'type'			=> 0,
				'repair_sn'		=> $repair_sn,
				'trade_price'	=> $v['trade_price'],
				'buying_price'	=> $v['buying_price'],
				'position'		=> $v['position'],
			];
		}
		return $this->validate('Goods.add')->saveAll($data);
	}
	/**
	 * 维修配件-真实库存
	 * 添加维修配件
	 */
	public function addTrueRepairGoods($repair_id)
	{
		$data = [];
		$rGoods = $this->getRepairGoods($repair_id);
		$this->delAllRepairGoods($repair_id);

		foreach($rGoods as $k => $v){
			// $number = $this->stockNumber($v['goods_id']);
			// if($number < $v['number']){
			// 	throw new Exception('配件-'. $v['goods_name'] . '：库存不足，请采购后添加');
			// }
			// $stock = $this->getStock($v['goods_id']);
			$data = $this->handleGoods($v, $data);
		}
		return $this->saveAll($data);
	}
	/**
	 * 维修配件
	 * 库存来源处理
	 */
	private function handleGoods($goods, $data = [])
	{
		$number1 = $this->stockNumber($goods['goods_id']);
		if($number1 < $goods['number']){
			throw new Exception('配件-'. $goods['goods_name'] . '：库存不足，请采购后添加');
		}
		$stock = $this->getStock($goods['goods_id']);
		$number = $goods['number'];//购买剩余量
		foreach($stock as $k => $v){
			if($number == 0) return $data;/*剩余量为0*/
			if($v['number'] > $number){/*批次库存大于剩余量*/
				$buy = $number;
			}
			$buy = $v['number'] > $number ? $number : $v['number'];//购买量
			$number = intval($number) - intval($buy);//跟新剩余量
			$data[] = [
				'stock_id'		=> $v['stock_id'],
				'repair_id'		=> $goods['repair_id'],
				'goods_id'		=> $v['goods_id'],
				'goods_sn'		=> $goods['goods_sn'],
				'goods_name'	=> $goods['goods_name'],
				'number'		=> $buy,
				'unit'			=> $goods['unit'],
				'selling_price'	=> $goods['selling_price'],
				'type'			=> 0,
				'repair_sn'		=> $goods['repair_sn'],
				'trade_price'	=> $goods['trade_price'],
				'buying_price'	=> $v['buying_price'],
				'position'		=> $v['position'],
			];
			/*@减少库存*/
			$this->cutGoodsNumber($v['stock_id'], $buy);
		}
		return $data;
	}
	/**
	 * 减少维修库存
	 */
	private function cutGoodsNumber($stock_id, $num)
	{
		return Db::name('stock')->where('stock_id',$stock_id)->setDec('number',$num);
	}
	/**
	 * 获取维修配件记录 
	 */
	private function getRepairGoods($repair_id)
	{
		return $this->where('repair_id',$repair_id)->select();
	}
	/**
	 * 删除维修配件记录
	 */
	private function delAllRepairGoods($repair_id)
	{
		return $this->where('repair_id',$repair_id)->delete();
	}
	/**
	 * 获取配件所有批次
	 */
	private function getStock($goods_id)
	{
		return Db::name('stock')
		->where('state',0)->where('is_show',0)->where('headquarters',0)->where('goods_id',$goods_id)->where('number','>',0)
		->order('addtime asc')->select();
	}
	/**
	 * 获取维修配件所有批次总库存
	 */
	private function stockNumber($goods_id)
	{
		return Db::name('stock')->where('state',0)->where('is_show',0)->where('headquarters',0)->where('goods_id',$goods_id)
		->where('number','>',0)->sum('number');
	}
	/**
	 * 维修配件增减
	 */
	public function upRepairGoods($goods, $repair_id, $repair_sn)
	{
		$add = [];
		$up = [];
		foreach($goods as $k => $v){
			if(isset($v['repair_goods_id'])){/*修改*/
				$up[] = [
					'repair_goods_id'	=> $v['repair_goods_id'],
					'number'			=> $v['num'],
				];
			}else{/*添加*/
				$add[] = [
					'stock_id'		=> $v['stock_id'],
					'repair_id'		=> $repair_id,
					'goods_id'		=> $v['goods_id'],
					'goods_sn'		=> $v['goods_sn'],
					'goods_name'	=> $v['goods_name'],
					'number'		=> $v['num'],
					'unit'			=> $v['unit'],
					'selling_price'	=> $v['selling_price'],
					'type'			=> 0,
					'repair_sn'		=> $repair_sn,
					'trade_price'	=> $v['trade_price'],
					'buying_price'	=> $v['buying_price'],
					'position'		=> $v['position'],
				];
			}
		}
		$this->saveAll($up);
		return $this->validate('Goods.add')->saveAll($add);
	}
	/**
	 * 维修配件返库
	 * 商品库存处理
	 * 增加--->减少配件库存
	 * 减少--->添加配件返库
	 * 删除--->添加配件返库
	 * @param array $goods 配件集合
	 * @param array $del_id 删除的配件id集合
	 * @param intger $repair_id 维修单id
	 */
	public function handleGoodsNumber($goods, $del_id, $repair_id)
	{
		$data = [];
		/*@修改*/
		foreach($goods as $k => $v){
			if(isset($v['repair_goods_id'])){/*修改*/
				if($v['num'] < $v['old_num']){/*减少配件--->返库*/
					$sgoods = $this->get($v['repair_goods_id']);
					$num = intval($v['old_num']) - intval($v['num']);
					$this->addStockRepair($sgoods, $num);
				}else if($v['num'] > $v['old_num']){/*增加---->减少商品库存*/
					$num = intval($v['num']) - intval($v['old_num']);
					$this->cutGoodsNumber($v['stock_id'],$num);
				}
			}else{/*新增--->减少商品库存*/
				$data = $this->editAddGoods($v, $data);
			}
		}
		/*添加--->维修配件*/
		$this->saveAll($data);
		/*@删除配件返库*/
		if($del_id && is_array($del_id)){
			foreach($del_id as $v){
				$sgoods = $this->where('repair_id',$repair_id)->where('stock_id','in',$del_id)->find();
				$this->addStockRepair($sgoods, $sgoods->number);
			}
		}
		
	}
	/**
	* 编辑时-新增维修配件 handleGoods
	*/
	private function editAddGoods($v, $data)
	{
		$number1 = Db::name('stock')->where('state',0)->where('is_show',0)->where('headquarters',0)->where('stock_id',$stock_id)->sum('number');
		if($number1 < $v['num']){
			throw new Exception('配件-'. $goods['goods_name'] . '：库存不足，请采购后添加');
		}
		$data[] = [
			'stock_id'		=> $v['stock_id'],
			'repair_id'		=> $v['repair_id'],
			'goods_id'		=> $v['goods_id'],
			'goods_sn'		=> $v['goods_sn'],
			'goods_name'	=> $v['goods_name'],
			'number'		=> $v['num'],
			'unit'			=> $v['unit'],
			'selling_price'	=> $v['selling_price'],
			'type'			=> 0,
			'repair_sn'		=> $v['repair_sn'],
			'trade_price'	=> $v['trade_price'],
			'buying_price'	=> $v['buying_price'],
			'position'		=> $v['position'],
		];
		return $data;
	}
	/**
	 * 维修配件返库
	 * @param array $goods 返库信息
	 */
	public function addStockRepair($goods, $num)
	{
		$data = [
			'stock_id'			=> $goods->stock_id,
			'goods_id'			=> $goods->goods_id,
			'goods_name'		=> $goods->goods_name,
			'number'			=> $num,
			'repair_sn'			=> $goods->repair_sn,
			'repair_id'			=> $goods->repair_id,
			'unit'				=> $goods->unit,
			'selling_price'		=> $goods->selling_price,
			'trade_price'		=> $goods->trade_price,
			'buying_price'		=> $goods->buying_price,
			'position'			=> $goods->position,
			'state'				=> 0,
			'addtime'			=> time(),
		];
		return Db::name('stockRepair')->insertGetId($data);
	}
	/**
	 * 删除维修配件
	 * @param  intger $repair_id 维修单id
	 */
	public function delRepairGoods($repair_id, $del_id)
	{
		return $this
		->where('repair_id',$repair_id)
		->where('stock_id','in',$del_id)
		->delete();
	}
	/**
	 * 获取选中维修配件商品列表
	 * @param array $where 查询条件
	 * @param string $order 排序条件
	 * @param intger $page 当前页数
	 * @param intger $row 每页条数
	 * @param string $search 关键字检索条件
	 */
	public function listData($where, $order, $page, $row, $search = '', $ty = null)
	{
		if($where == false) return [];
		if($ty == 'edit'){
			return self::stockData($where, $order, $page, $row, $search);
		}
		return self::allData($where, $order, $page, $row, $search);
	}
	/**
	* 商品纬度
	* 商品列表
	*/
	private function allData($where, $order, $page, $row, $search)
	{
		if( $row == 'limit' ){
			return $this->alias('rg')
			->join('mps_goods g','g.goods_id = rg.goods_id',"LEFT")
			->join('mps_stock s','g.goods_id = s.goods_id','LEFT')
			->field('rg.number as num,rg.repair_goods_id,g.*,s.*')
			->where($search)->where($where)
			->order($order)
			->group('rg.repair_goods_id')
			->select();
		}
		return $this->alias('rg')
			->join('mps_goods g','g.goods_id = rg.goods_id',"LEFT")
			->join('mps_stock s','g.goods_id = s.goods_id','LEFT')
			->field('rg.number as num,rg.repair_goods_id,g.*,s.*')
			->where($search)->where($where)
			->order($order)
			->page($page, $row)
			->group('rg.repair_goods_id')
			->select();
	}
	/**
	* 批次纬度
	* 商品列表
	*/
	private function stockData($where, $order, $page, $row, $search)
	{
		if( $row == 'limit' ){
			return $this->alias('rg')
			->join('mps_goods g','g.goods_id = rg.goods_id',"LEFT")
			->join('mps_stock s','rg.stock_id = s.stock_id','LEFT')
			->field('rg.number as num,rg.repair_goods_id,g.*,s.*')
			->where($search)->where($where)
			->order($order)
			->group('rg.repair_goods_id')
			->select();
		}
		return $this->alias('rg')
			->join('mps_goods g','g.goods_id = rg.goods_id',"LEFT")
			->join('mps_stock s','rg.stock_id = s.stock_id','LEFT')
			->field('rg.number as num,rg.repair_goods_id,g.*,s.*')
			->where($search)->where($where)
			->order($order)
			->page($page, $row)
			->group('rg.repair_goods_id')
			->select();
	}
	/**
	 * 获取选中维修配件商品总条数
	 * @param array $where 查询条件
	 * @param string $order 排序条件
	 * @param string $search 关键字检索条件
	 */
	public function listCount($where, $order, $search = '', $ty = null)
	{
		if($where == false) return 0;
		return $this->where($search)->where($where)->order($order)->count();
	}
	/**
	 * 设置model对应的表名
	 */
	public function setTable($table)
	{
		$this->table = $table;
	}
	/**
	 * 维修配件子分类集合
	 */
	public function getRepairCat()
	{
		return Db::name('category')->where('fid',config('parameter.repair_cat_id'))->select();
	}
	/**
	 * 获取器
	 */
	public function getCategoryNameAttr($value, $data)
	{
		return Db::name('category')->where('category_id',$data['category_id'])->value('category_name');
	}
	public function getCateNameAttr($value, $data)
	{
		return Db::name('category')->where('category_id',$data['cat_id'])->value('category_name');
	}
	public function getOldNumAttr($value, $data){
		return $data['num'];
	}
	public function getNumberAttr($value, $data){
		if(isset($data['stock_id']) && $data['stock_id'] > 0) return $value;
		return Db::name('stock')->where('goods_id',$data['goods_id'])->where('is_show',0)->where('state',0)->where('headquarters',0)->sum('number');
	}
	/************************************** 私有 ********************************************/

	/**
	 * 减少商品库存
	 */
	private function cutGoodsNumber1($goods_id, $num)
	{
		return Db::name('stock')->where('goods_id',$goods_id)->setDec('number',$num);
	}
	
}